package com.atguigu.test;

/**
 * 一个链表 123456 实现倒叙
 */
public class LinkedListReversal {
    /**
     * 反转链表的方法
     */
    public static ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;

        while (curr != null) {
            ListNode nextTemp = curr.next;  //临时保存下一个节点
            curr.next = prev;               //反转当前节点的指针
            prev = curr;                    //移动prev指针到当前节点
            curr = nextTemp;                //移动curr指针到下一个节点
        }
        return prev;    //新的头节点
    }

    //打印链表的方法
    public static void printList(ListNode head) {
        ListNode curr = head;
        while (curr != null) {
            System.out.print(curr.val + " ");
            curr = curr.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        System.out.print("Original List: ");
        printList(head);

        //反转链表
        ListNode reversedHead = reverseList(head);
        System.out.print("Reversed List: ");
        printList(reversedHead);
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}
